const fs = require('fs');
const path = require('path');
const uploadDir = path.join(process.cwd(), 'uploads/')
const dataPath = path.join(process.cwd(), 'common/data.json')
const logPath = path.join(process.cwd(), 'common/log.txt')
const crypto = require('crypto');

module.exports = {
    // upload目录
    uploadDir,
    // 初始化创建upload目录
    createMain: () => {
        if (!fs.existsSync(uploadDir)) {
            fs.mkdirSync(uploadDir)
        }
    },
    // 创建用户子文件夹
    createContext: (id, name) => {
        let userPath = path.join(uploadDir, `/${id}/${name}/`)
        if (!fs.existsSync(userPath)) {
            fs.mkdirSync(userPath)
        }
    },
    // 读token
    readData: (id) => {
        let data = JSON.parse(fs.readFileSync(dataPath))
        if (id in data) {
            return data[id]
        } else {
            return false
        }
    },
    // 写token
    writeData: (id, md5) => {
        let data = JSON.parse(fs.readFileSync(dataPath))
        data[id] = md5
        fs.writeFileSync(dataPath, JSON.stringify(data))
        return true
    },
    // 对称加密
    // aesEncrypt: (data, key) => {
    //     const cipher = crypto.createCipheriv('aes-128-cbc', key, '8e13f50acdff55bc');
    //     var crypted = cipher.update(data, 'utf8', 'hex');
    //     crypted += cipher.final('hex');
    //     return crypted;
    // },
    // 对称解密
    // aesDecrypt: (encrypted, key) => {
    //     const decipher = crypto.createDecipheriv('aes-128-cbc', key, '8e13f50acdff55bc');
    //     var decrypted = decipher.update(encrypted, 'hex', 'utf8');
    //     decrypted += decipher.final('utf8');
    //     return decrypted;
    // },
    // md5加密
    createMD5: (data) => {
        const hash = crypto.createHash('md5');
        hash.update(data);
        return hash.digest('hex')
    },
    // 输出日志
    pushLog: (id, path, name, operate, status) => {
        let time = new Date()
        let log = `..${time},${id}:${path}/${name},${operate}|${status}..`
        global.mylog.push(log)
    },
    // 保存日志
    saveLog: () => {
        fs.appendFile(logPath, JSON.stringify(global.mylog), 'utf8', function (err, ret) {
            if (err) {
                console.log('输入log出错', err)
            } else {
                global.mylog = []
            }
        })
    }
}